package com.erdos.hyt.mall.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.*;
import java.util.Properties;

@Order(1)
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
	public static String confile = "druid.properties";
	public static Properties properties = null;

	static {
		properties = new Properties();
		InputStream inputStream = null;
		try {
			confile = DataSourceConfig.class.getClassLoader().getResource("").getPath() + confile;
			File file = new File(confile);
			inputStream = new BufferedInputStream(new FileInputStream(file));
			properties.load(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Bean(name = "defualtDataSource", destroyMethod = "close", initMethod = "init")
	@Primary
	public DataSource dataSource() {
		DataSource dataSource;
		try {
			dataSource = DruidDataSourceFactory.createDataSource(properties);
			return dataSource;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Bean
	public DataSourceTransactionManager dataSourceTransactionManager(DataSource defualtDataSource) {
		return new DataSourceTransactionManager(defualtDataSource);
	}

}
